package org.jwd.storage.mbp.config;

import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWTUtil;
import lombok.Getter;
import org.jwd.core.entity.AuthEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author vizz
 * @since 2022/5/17 14:08
 * 鉴权相关的逻辑都写在这里
 * 1.鉴权方式auth-type：  session jwt
 * 2.存储方式store-type：  db  cache  redis
 * 3.失效时间invalid-time：  默认30分钟。因为判断时间比查库快，所以我们通过比较时间来验证是否过期
 * 4.密码重试次数 pwd-retry：    默认5次，可设置
 * 5.验证码出现次数captcha-retry ：   默认3次后，可设置
 */
@Component
@Getter
public class DynamicValidationService {

    @Value("${sprout.auth.auth-type:session}")
    private String authType;

    @Value("${sprout.auth.store-type:db}")
    private String storeType;

    @Value("${sprout.auth.invalid-time:30}")
    private int invalidTime;

    @Value("${sprout.auth.pwd-retry:5}")
    private int pwdRetry;

    @Value("${sprout.auth.captcha-retry:3}")
    private int captchaRetry;

    @Value("${sprout.auth.verify-key:jwdsprout513}")
    private String verifyKey;

    public void addValidationInfo(AuthEntity authEntity){
        if("session".equalsIgnoreCase(authType)){
            authEntity.setValidation(IdUtil.fastSimpleUUID())
                    .setType(1);
        }else if("jwt".equalsIgnoreCase(authType)){
            Map<String, Object> headers = new HashMap<>();
            Map<String, Object> payloads = new HashMap<>();
            byte[] key = verifyKey.getBytes();
            String token = JWTUtil.createToken(headers, payloads, key);
            authEntity.setValidation(token)
                    .setType(2);
        }
    }
}
